package com.myh.gulimall.authserver.service.impl;

import com.myh.common.constant.AuthConstant;
import com.myh.gulimall.authserver.feign.ThirdPartyFeignService;
import com.myh.gulimall.authserver.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;


/**
 * @Description: // 类说明，在创建类时要填写
 * @ClassName: LoginServiceImpl    // 类名，会自动填充
 * @Author: MYH          // 创建者
 * @Date: 2024/5/30 19:13   // 时间
 * @Version: 1.0     // 版本
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Boolean sendCode(String phone) {
        //1、60秒内验证码防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.SmsEnum.SMS_CODE_CACHE_PREFIX.getSmsCodeCachePrefix() + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000){
                return false;
            }
        }

        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String code = stringBuilder.toString() + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthConstant.SmsEnum.SMS_CODE_CACHE_PREFIX.getSmsCodeCachePrefix() + phone, code, 10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone ,code.split("_")[0]);
        return true;
    }
}
